import datetime
import os
from datetime import date, timedelta
from typing import Tuple, List

from pandas import DataFrame
import akshare as ak
import pandas as pd

from utils.data_source import mysql_db, query, update
from wxauto import WeChat


def clear_today_his():
    start_date = query(f"""select max(data) as start_date from world.history""")['start_date'][0]
    if not start_date:
        start_date = date.today()
    end_date = (start_date + timedelta(weeks=-10)).__format__("%Y%m%d")
    start_date = start_date.__format__("%Y%m%d")
    update(f"""delete from world.history where data = {start_date} or data < {end_date}""")


def insert(hist: DataFrame, name):
    args = list()
    for his in hist.values:
        args.append((name,) + tuple(his))
    con = mysql_db()
    with con.cursor() as cursor:
        sql = f"""INSERT INTO world.history(name,data,symbol,open, close, high, low,cjl,cje, zf,zdf,zde,hsl) 
        VALUES (%s, %s, %s,%s, %s, %s, %s,%s,%s,%s,%s,%s,%s)"""
        cursor.executemany(query=sql, args=args)
        con.commit()


def insert_gf(hist: DataFrame, symbol, name):
    args = list()
    for his in hist.values:
        args.append((symbol, name) + tuple(his))
    con = mysql_db()
    with con.cursor() as cursor:
        sql = f"""INSERT INTO world.gf_analysis(symbol,data) 
                VALUES (%s, %s)"""
        cursor.executemany(query=sql, args=args)
        con.commit()


def insert_gf_hc(hist: DataFrame):
    args = list()
    for his in hist.values:
        if his[1]:
            args.append((his[1], his[2], his[0], his[3], his[4], his[5]))
    con = mysql_db()
    with con.cursor() as cursor:
        sql = f"""INSERT INTO world.gf_analysis(symbol,name,data,zde,min,cjl) 
                VALUES (%s, %s,%s,%s,%s,%s)"""
        cursor.executemany(query=sql, args=args)
        con.commit()


def insert_current(hist: DataFrame):
    today = date.today().__format__("%Y%m%d")
    args = list()
    for i in range(len(hist)):
        his = hist.iloc[i]
        if check(his):
            continue
        args.append((today,) + tuple(his.values))
    con = mysql_db()
    with con.cursor() as cursor:
        sql = f"""INSERT INTO world.history(data,symbol,name,close,open,high,low,cjl,cje, zf,zdf,zde,hsl) 
                VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
        cursor.executemany(query=sql, args=args)
        con.commit()


def data_update(symbol: str, name: str):
    end_date = date.today() + timedelta(days=1)
    start_date = end_date + timedelta(weeks=-26)
    hist = ak.stock_zh_a_hist(symbol=symbol, period='daily', start_date=start_date.__format__("%Y%m%d"),
                              end_date=end_date.__format__("%Y%m%d"), adjust='qfq')
    insert(hist, name)


def query_hist(dataa) -> tuple[DataFrame, list[str]]:
    data = query(
        f"""select concat(a.symbol,name) as name,data,close,open,high,low,hsl from world.history a where data <= '{dataa}' order by a.symbol,data desc""")
    grouped = data.groupby('name')
    # 将分组后的数据拆分到多个DataFrame中
    dataframes = {name: group for name, group in grouped}
    df = None

    def rename(x: str, name: str) -> str:
        if x != 'data':
            return name + x
        return x

    for name, data in dataframes.items():
        del data['name']
        data = data.rename(columns=lambda x: rename(x, name))
        if df is None:
            df = data
        else:
            df = pd.merge(df, data, on='data', how='inner')
    columns = df.columns.values
    return df, columns[1:]


def check(company):
    symbol = company['代码']
    name = company['名称']
    price = company['最新价']
    hsl = company['换手率']
    cje = company['成交额']
    return (str(symbol).startswith('30') or str(symbol).startswith('688') or str(name).startswith('C') or str(
        name).startswith('N') or 'ST' in name or '退' in name or price is None or float(price) < 3
            or float(price) > 30 or float(hsl) < 3 or float(hsl) > 30)


def update_gf_analysis():
    # 删除今日数据避免重复
    sql = """delete from analysis where data >= (select distinct data from world.history order by data desc limit 1 offset 1)"""
    update(sql=sql)

    # 突破分析
    sql = """INSERT INTO analysis (select '突破', a.data,a.name,a.symbol,a.zdf,a.zf,0 as px,a.cjl/d.cjl as lb,e.zdf as result from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join history e on e.data = (select distinct data from world.history where data > a.data order by data limit 1) and e.symbol = a.symbol left join (select * from (select symbol, max(close+0) as close,count(close) as count from history aa,
    (select distinct data from world.history order by data desc limit 9 offset 1) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.close = b.close and a.data =
    (select distinct data from world.history order by data desc limit 1 offset 1) order by result + 0)"""
    update(sql=sql)

    # 抄底分析
    sql = """INSERT INTO analysis (select '抄底',a.data,a.name,a.symbol,a.zdf,a.zf,0 as px,a.cjl/d.cjl as lb,e.zdf as result from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join history e on e.data = (select distinct data from world.history where data > a.data order by data limit 1) and e.symbol = a.symbol left join (select * from (select symbol, min(close+0) as close,count(close) as count from history aa,
    (select distinct data from world.history order by data desc limit 9 offset 1) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.close = b.close and a.data =
    (select distinct data from world.history order by data desc limit 1 offset 1) order by result + 0)"""
    update(sql=sql)

    # 均线突破
    sql = """INSERT INTO analysis (select '均突',a.data,a.name,a.symbol,a.zdf,a.zf,0 as px,a.cjl/d.cjl as lb,e.zdf as result from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join history e on e.data = (select distinct data from world.history where data > a.data order by data limit 1) and e.symbol = a.symbol left join (select * from (select symbol, max(close+0) as close, avg(close+0) as avgg, count(close) as count from history aa,
    (select distinct data from world.history order by data desc limit 9 offset 1) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.close > b.avgg and b.close > a.close and a.zdf+0 >0 and a.data =
    (select distinct data from world.history order by data desc limit 1 offset 1) order by result + 0)"""
    update(sql=sql)

    sql = """select type,data, avg(result+0) as avgg from analysis where data >=(select distinct data from world.history order by data desc limit 1 offset 5) group by data, type order by type, data"""
    analysis = query(sql=sql)
    # WeChat().sendMsg(who='文件传输助手', msg=str(analysis))


def update_analysis(analysis_tail: bool):
    tail = None
    if analysis_tail:
        sql = """select avg(result+0) as avgg from analysis where data >=(select distinct data from world.history order by data desc limit 1 offset 1) group by data, type order by type, data"""
        tail = query(sql=sql)

    # 删除今日数据避免重复
    sql = """delete from analysis where data >= (select distinct data from world.history order by data desc limit 1 offset 1)"""
    update(sql=sql)

    # 突破分析
    sql = """INSERT INTO analysis (select '突破', a.data,a.name,a.symbol,a.zdf,a.zf,0 as px,a.cjl/d.cjl as lb,e.zdf as result from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join history e on e.data = (select distinct data from world.history where data > a.data order by data limit 1) and e.symbol = a.symbol left join (select * from (select symbol, max(close+0) as close,count(close) as count from history aa,
    (select distinct data from world.history order by data desc limit 9 offset 1) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.close = b.close and a.data =
    (select distinct data from world.history order by data desc limit 1 offset 1) order by result + 0)"""
    update(sql=sql)

    # 抄底分析
    sql = """INSERT INTO analysis (select '抄底',a.data,a.name,a.symbol,a.zdf,a.zf,0 as px,a.cjl/d.cjl as lb,e.zdf as result from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join history e on e.data = (select distinct data from world.history where data > a.data order by data limit 1) and e.symbol = a.symbol left join (select * from (select symbol, min(close+0) as close,count(close) as count from history aa,
    (select distinct data from world.history order by data desc limit 9 offset 1) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.close = b.close and a.data =
    (select distinct data from world.history order by data desc limit 1 offset 1) order by result + 0)"""
    update(sql=sql)

    # 均线突破
    sql = """INSERT INTO analysis (select '均突',a.data,a.name,a.symbol,a.zdf,a.zf,0 as px,a.cjl/d.cjl as lb,e.zdf as result from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join history e on e.data = (select distinct data from world.history where data > a.data order by data limit 1) and e.symbol = a.symbol left join (select * from (select symbol, max(close+0) as close, avg(close+0) as avgg, count(close) as count from history aa,
    (select distinct data from world.history order by data desc limit 9 offset 1) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.close > b.avgg and b.close > a.close and a.zdf+0 >0 and a.data =
    (select distinct data from world.history order by data desc limit 1 offset 1) order by result + 0)"""
    update(sql=sql)

    sql = """select type,data, avg(result+0) as avgg from analysis where data >=(select distinct data from world.history order by data desc limit 1 offset 5) group by data, type order by type, data"""
    analysis = query(sql=sql)
    # WeChat().sendMsg(who='文件传输助手', msg=str(analysis))

    if analysis_tail:
        sql = """select avg(result+0) as avgg from analysis where data >=(select distinct data from world.history order by data desc limit 1 offset 1) group by data, type order by type, data"""
        tail['bvgg'] = query(sql=sql)['avgg']
        tail['tail'] = tail['bvgg'] - tail['avgg']
        WeChat().sendMsg(who='文件传输助手', msg=str(tail))


# 止损止盈策略分析
def zszyfx():
    count = """select count(1) from analysis left join world.history bl on analysis.name = bl.name and bl.data =analysis.data left join history d on d.symbol=bl.symbol and d.data = (select distinct data from world.history where data > bl.data order by data limit 1)
            where type = '抄底' and d.data is not null"""
    count = query(sql=count)[0][0]
    for zy in range(1, 6):
        for zs in range(1, 6):
            zy = 1 + 0.01 * zy
            zs = 1 - 0.01 * zy
            sql = f"""select avg((d.high-bl.close)/bl.close) as avgg,count(1) as cc from analysis left join world.history bl on analysis.name = bl.name and bl.data =analysis.data left join history d on d.symbol=bl.symbol and d.data = (select distinct data from world.history where data > bl.data order by data limit 1) left join history f on f.symbol=bl.symbol and f.data = (select distinct data from world.history where data > bl.data order by data limit 1 offset 1)
            where type = '抄底' and f.data is not null and d.high < (bl.close * {zy})"""
            res = query(sql=sql)
            avgg = res.iloc[0][0]
            ct = res.iloc[0][1]
            print(str(zy) + "0.01" + str(zy * (count - ct) + avgg * ct))


def suggest_gg():
    args = list()
    sql = f"""select * from (select b.*,(b.close - a.minlow) /(a.maxlow - a.minlow) as min,(b.cjl/a.avgcjl) as avgcjl from (select max(low+0) as maxlow, min(low+0) as minlow, min(cjl+0) as mincjl, avg(cjl+0) as avgcjl, symbol from history
                 group by symbol) a 
                left join history b on a.symbol = b.symbol where b.data = (select distinct data from history order by data desc limit 1)
                and a.mincjl = b.cjl
                order by (b.close - a.minlow) / (a.maxlow - a.minlow)) a
                where min > 0
                and min < 0.2
                order by avgcjl + 0"""
    suggest = query(sql=sql)
    if len(suggest) > 0:
        for his in suggest.values:
            args.append(his)
    if len(args) == 0:
        args = "今日没有合适标的"

    try:
        WeChat().sendMsg(who='文件传输助手', msg=str(args))
    except Exception as r:
        print(r)
    print(str(args))


def suggest_cjl_hc(index: int):
    sql_hc = f"""select a.*,b.zdf from (select * from (select b.*,ROUND(0.5 * b.close/a.minlow - 0.5 ,2) as min,ROUND(b.cjl/a.mincjl -1,2) as avgcjl from (select max(high+0) as maxlow, min(low+0) as minlow,avg(close+0) as avglow, min(cjl+0) as mincjl, max(cjl+0) as maxcjl, avg(cjl+0) as avgcjl, symbol from history
     where zdf > -8
    and zdf < 8 and data <= (select distinct data from history order by data desc limit 1 offset {index})
      and data > (select distinct data from history order by data desc limit 1 offset {index + 30})group by symbol) a
    left join history b on a.symbol = b.symbol and b.data = (select distinct data from history order by data desc limit 1 offset {index})) a
    where zdf > -8
    and zdf < 0
    order by avgcjl,min,a.zdf+0 desc limit 3) a left join history b on a.symbol = b.symbol and a.`data` = b.`data` - 1"""
    suggest_cjl = query(sql=sql_hc)
    # insert_gf_hc(suggest_cjl)
    print(suggest_cjl.to_csv(header=None, index=False), end='')


def suggest_hc(test: bool = False):
    if test:
        update("""truncate gf_analysis""")
        for ind in range(50, -1, -1):
            suggest_cd(ind, test=True)
    else:
        suggest_cd(0)


def suggest_cd(index: int, test: bool = False):
    sql_hc = f"""select * from (select b.*,ROUND(0.5 * b.close/a.minlow ,3) * 2 as min,ROUND(b.cjl/a.maxcjl,2) as avgcjl from (select max(high+0) as maxlow, min(low+0) as minlow,avg(close+0) as avglow, min(cjl+0) as mincjl, max(cjl+0) as maxcjl, avg(cjl+0) as avgcjl, symbol from history
     where data <= (select distinct data from history order by data desc limit 1 offset {index})
      and data > (select distinct data from history order by data desc limit 1 offset {index + 30}) group by symbol) a
    left join history b on a.symbol = b.symbol and b.data = (select distinct data from history order by data desc limit 1 offset {index})) a
    where zdf > -8 order by min + 0 , avgcjl + 0 limit 10"""
    suggest_min = query(sql=sql_hc)
    if test:
        insert_gf_hc(suggest_min[["data", "symbol", "name", "zdf", "min", "avgcjl"]])
    else:
        suggest_min[["symbol", "name", "zdf", "min", "avgcjl"]].to_csv(header=None, index=False, encoding='utf-8',
                                                                       path_or_buf="C:\\code\\sada\\data.csv", sep='\t')
        os.system('cd C:\\code\\sada\\&&git commit -a -m "0"&&git push')


# gf
def suggest_gf(index: int = 0, test: bool = False):
    if not is_con() and not test:
        return
    # sql = f"""SELECT b.zdf, a.zdf + 0 as result FROM world.history a,world.history b
    #                where a.symbol = b.symbol
    #                and a.data = (select distinct data from world.history order by data desc limit 1 offset {index})
    #                and b.data = (select distinct data from world.history order by data desc limit 1 offset {index + 1})
    #                and b.zdf + 0 < 8 and b.zdf + 0 > -8 and a.zdf is not null ORDER BY b.zdf+0"""
    # suggest_s = query(sql=sql)
    # sql = f"""SELECT b.cjl/c.cjl as lb, a.zdf+0 as result FROM world.history a,world.history b,world.history c
    #                where a.symbol = b.symbol
    #                  and a.symbol = c.symbol
    #                  and a.data = (select distinct data from world.history order by data desc limit 1 offset {index})
    #                and b.data = (select distinct data from world.history order by data desc limit 1 offset {index + 1})
    #                and c.data = (select distinct data from world.history order by data desc limit 1 offset {index + 2})
    #                and b.zdf + 0 < 8 and b.zdf + 0 > -8 and a.zdf is not null ORDER BY b.cjl/c.cjl"""
    # suggest_lb = query(sql=sql)
    # param = list()
    # for level in range(5, 0, -1):
    #     suggest_s['temp'] = suggest_s['result'] - 0.5 * level
    #     start_index, end_index, max_sum = max_sub_list(suggest_s[['temp']].T.values[0])
    #     zdf_min = suggest_s.iloc[start_index][0]
    #     zdf_max = suggest_s.iloc[end_index][0]
    #
    #     suggest_lb['temp'] = suggest_lb['result'] - 0.5 * level
    #     start_index, end_index, max_sum = max_sub_list(suggest_lb[['temp']].T.values[0])
    #     lb_min = suggest_lb.iloc[start_index][0]
    #     lb_max = suggest_lb.iloc[end_index][0]
    #     param.append([zdf_min, zdf_max, lb_min, lb_max])
    #
    # args = list()
    # for zdf_i in range(len(param)):
    #     if len(args) > 0:
    #         break
    #     for lb_i in range(2):
    #         if zdf_i + lb_i == len(param):
    #             break
    #         zdf_min = param[zdf_i][0]
    #         zdf_max = param[zdf_i][1]
    #         lb_min = param[zdf_i + lb_i][2]
    #         lb_max = param[zdf_i + lb_i][3]
    #         sql = f"""SELECT a.symbol as result FROM world.history a,world.history b
    #                 where a.symbol = b.symbol
    #                 and a.zdf+0 >= {zdf_min} and a.zdf+0 <= {zdf_max} and a.cjl/b.cjl >= {lb_min} and a.cjl/b.cjl <= {lb_max}
    #                 and a.data = (select distinct data from world.history order by data desc limit 1 offset {index})
    #                 and b.data = (select distinct data from world.history order by data desc limit 1 offset {index + 1})
    #                 order by a.zdf """
    #         suggest = query(sql=sql)
    #         if len(suggest) > 0:
    #             for his in suggest.values:
    #                 # args.append(his[0])
    #                 v = 1
    #             break
    args = list()
    if len(args) == 0:
        sql = f"""SELECT a.symbol as result,a.cjl/b.cjl as lb FROM world.history a,world.history b
                   where a.symbol = b.symbol
                   and a.data = (select distinct data from world.history order by data desc limit 1  offset {index})
                   and b.data = (select distinct data from world.history order by data desc limit 1  offset {index + 1})
                   and a.zdf + 0 < 4 and a.zdf + 0 > 2.5
                   and b.zdf + 0 < 9 and b.zdf + 0 > -9
                   and a.hsl + 0 < 3
                   order by a.cjl/b.cjl limit 1"""
        suggest = query(sql=sql)
        if len(suggest) > 0:
            for his in suggest.values:
                args.append(his)
                v = 1

    for i in range(len(args)):
        if len(args) <= 5:
            break
        del args[i % 2 - 1]
    if len(args) == 0:
        args = "今日没有合适标的"
    else:
        for sym in args:
            sql = f"""INSERT INTO world.gf_analysis(symbol,name,data) VALUES ('{sym[0]}','{sym[1]}',(select distinct data from world.history order by data desc limit 1 offset {index}))"""
            update(sql=sql)

        for sym in args:
            args = list()
            args.append(sym[0])
    try:
        WeChat().sendMsg(who='文件传输助手', msg=str(args))
    except Exception as r:
        print(r)
        print(str(args))


def suggest(param: list):
    sql = """select * from (select avg(result + 0) as avgg from analysis where data >= (select distinct data from world.history order by data desc limit 1 offset 1) group by data, type order by type, data) a where a.avgg > 0.5"""
    suggest = query(sql=sql)
    if len(suggest) == 0:
        args = "整体行情太差,空仓等机会"
        WeChat().sendMsg(who='文件传输助手', msg=str(args))
        return
    zdf_min = param[0]
    zdf_max = param[1]
    lb_min = param[2]
    lb_max = param[3]
    sug_type = param[4]
    if sug_type == '抄底':
        sql = f"""select a.symbol,a.name,a.cjl/d.cjl as lb from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join (select * from (select symbol, min(close+0) as close,count(close) as count from history aa,
        (select distinct data from world.history order by data desc limit 9) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.symbol not like '300%' and a.symbol not like '688%' and a.close = b.close and  a.zdf+0 > {zdf_min} and a.zdf+0 < {zdf_max} and  a.cjl/d.cjl > {lb_min} and a.cjl/d.cjl < {lb_max} and a.data =
        (select distinct data from world.history order by data desc limit 1) order by (a.zdf+0)"""
    if sug_type == '突破':
        sql = f"""select a.symbol,a.name,a.cjl/d.cjl as lb from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join (select * from (select symbol, max(close+0) as close,count(close) as count from history aa,
        (select distinct data from world.history order by data desc limit 9) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.symbol not like '300%' and a.symbol not like '688%' and a.close = b.close and a.zdf+0 > {zdf_min} and a.zdf+0 < {zdf_max} and  a.cjl/d.cjl > {lb_min} and a.cjl/d.cjl < {lb_max} and a.data =
        (select distinct data from world.history order by data desc limit 1) order by (a.zdf+0)"""
    if sug_type == '均突':
        sql = f"""select a.symbol,a.name,a.cjl/d.cjl as lb from history a left join history d on d.data = (select distinct data from world.history where data < a.data order by data desc limit 1) and d.symbol = a.symbol left join (select * from (select symbol, max(close+0) as close,avg(close+0) as avgg, count(close) as count from history aa,
        (select distinct data from world.history order by data desc limit 9) bbb where aa.data = bbb.data group by symbol) bb where bb.count = 9) b on a.symbol = b.symbol where a.symbol not like '300%' and a.symbol not like '688%' and a.close > b.avgg and b.close > a.close and a.zdf+0 > {zdf_min} and a.zdf+0 < {zdf_max} and  a.cjl/d.cjl > {lb_min} and a.cjl/d.cjl < {lb_max} and a.data =
        (select distinct data from world.history order by data desc limit 1) order by (a.zdf+0)"""
    suggest = query(sql=sql)
    size = len(suggest)
    args = list()
    for his in suggest.values:
        args.append(his[0])
    for i in range(len(args)):
        if len(args) <= 5:
            break
        del args[i % 2 - 1]
    if size == 0:
        args = "今日没有合适标的"
    WeChat().sendMsg(who='文件传输助手', msg=str(args))


def init_gf_pram():
    sql = f"""SELECT b.zdf ,a.zdf+0 as result FROM world.history a,world.history b
                where a.symbol = b.symbol and a.data = (select max(data) from world.history)
                and b.data = (select distinct data from world.history order by data desc limit 1 offset 1)
                and b.zdf + 0 < 8 and b.zdf + 0 > -8 and a.zdf is not null ORDER BY b.zdf+0"""
    suggest_s = query(sql=sql)
    sql = f"""SELECT b.cjl/c.cjl as lb,a.zdf+0 as result FROM world.history a,world.history b,world.history c
                where a.symbol = b.symbol
                  and a.symbol = c.symbol
                  and a.data = (select max(data) from world.history)
                and b.data = (select distinct data from world.history order by data desc limit 1 offset 1)
                and c.data = (select distinct data from world.history order by data desc limit 1 offset 2)
                and b.zdf + 0 < 8 and b.zdf + 0 > -8 and a.zdf is not null ORDER BY b.cjl/c.cjl"""
    suggest_lb = query(sql=sql)
    result = list()
    for level in range(6, 0, -1):
        suggest_s['temp'] = suggest_s['result'] - 0.5 * level
        start_index, end_index, max_sum = max_sub_list(suggest_s[['temp']].T.values[0])
        zdf_min = suggest_s.iloc[start_index][0]
        zdf_max = suggest_s.iloc[end_index][0]

        suggest_lb['temp'] = suggest_lb['result'] - 0.5 * level
        start_index, end_index, max_sum = max_sub_list(suggest_lb[['temp']].T.values[0])
        lb_min = suggest_lb.iloc[start_index][0]
        lb_max = suggest_lb.iloc[end_index][0]
        result.append([zdf_min, zdf_max, lb_min, lb_max])
    return result


def init_pram():
    # 根据两天之内策略数据
    sql = f"""select type, avg(result+0) as avgg from analysis where data >=(select distinct data from world.history order by data desc limit 1 offset 1) group by type order by avg(result+0) desc limit 1"""
    suggest_s = query(sql=sql)
    sug_type = suggest_s.iloc[0][0]

    sql = f"""SELECT zdf, result+0 as result FROM world.analysis t where data >= (select distinct data from world.history order by data desc limit 1 offset 10)
    and type = '{sug_type}' and zdf + 0 < 8 and zdf + 0 > -8  and result is not null ORDER BY zdf+0"""
    suggest_s = query(sql=sql)
    start_index, end_index, max_sum = max_sub_list(suggest_s[['result']].T.values[0])
    zdf_min = suggest_s.iloc[start_index][0]
    zdf_max = suggest_s.iloc[end_index][0]

    sql = f"""SELECT lb, result+0 as result FROM world.analysis t where data >= (select distinct data from world.history order by data desc limit 1 offset 10)
    and type = '{sug_type}' and zdf + 0 < 8 and zdf + 0 > -8  and result is not null ORDER BY lb+0"""
    suggest_s = query(sql=sql)
    start_index, end_index, max_sum = max_sub_list(suggest_s[['result']].T.values[0])
    lb_min = suggest_s.iloc[start_index][0]
    lb_max = suggest_s.iloc[end_index][0]
    result = [zdf_min, zdf_max, lb_min, lb_max, sug_type]
    return result


def max_sub_list(lis: list):
    start = [0] * len(lis)
    dp = [0] * len(lis)
    for index in range(len(lis)):
        if dp[index - 1] > 0:
            dp[index] = lis[index] + dp[index - 1]
            start[index] = start[index - 1]
        else:
            dp[index] = lis[index]
            start[index] = index
    start_index = 0
    end_index = 0
    max_sum = 0
    for index in range(len(lis)):
        if max_sum < dp[index]:
            start_index = start[index]
            end_index = index
            max_sum = dp[index]
    return start_index, end_index, max_sum


# 是否开市
def is_con():
    today = date.today().__format__("%Y%m%d")
    start_date = query(f"""select max(data) as start_date from world.history""")['start_date'][0]
    return today == start_date.__format__("%Y%m%d")
